package conchmusic.conchmusicclient.activity;

import android.Manifest;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.adapter.LocalListAdapter;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.pojo.SortMusic;
import conchmusic.conchmusicclient.util.InitPlayBar;
import conchmusic.conchmusicclient.util.PinyinComparator;
import conchmusic.conchmusicclient.util.ScanMusic;
import conchmusic.conchmusicclient.util.SongGetScanMusic;
import conchmusic.conchmusicclient.view.PlayBar;
import conchmusic.conchmusicclient.view.SideBar;

public class LocalMusicActivity extends AppCompatActivity {
    private ListView listView;
    private List<Song> localMusics;
    private LocalListAdapter listViewAdapter;
    private ClientControl clientControl;
    private MyDBHelp myDBHelp;
    private LocalReceiver localReceiver;
    private PlayBar playBar;
    private String[] list;
    private Intent intent;
    private Button btn_play;
    private SideBar sideBar;
    private TextView dialog;
    private PinyinComparator pinyinComparator;
    private boolean isOnStart;
    private InitPlayBar initPlayBar;
    private TextView textView;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_music);
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        sideBar=(SideBar)findViewById(R.id.local_side_bar);
        dialog=(TextView)findViewById(R.id.local_sort_dialog);
        sideBar.setTextView(dialog);
        listView=(ListView)findViewById(R.id.listview_mymusic);
        listView.setDividerHeight(0);
        //播放状态
        btn_play=(Button)findViewById(R.id.playbar_play);
        pinyinComparator=new PinyinComparator();
        myDBHelp=new MyDBHelp(this,"demon",null,1);
        clientControl=new ClientControl(myDBHelp);
        localMusics=new ArrayList<>();
        initAdapter();
        playBar=(PlayBar)findViewById(R.id.localMusic_playbar);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                initPlayBar.itemInitPlaybar();
                intent=playMusic(position,list);
                Log.i("click list.size",list.length+"...");
                startService(intent);
                btn_play.setBackgroundResource(R.mipmap.ic_pause);
            }
        });

        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int position = listViewAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    listView.setSelection(position );
                }
            }
        });
        isOnStart=true;

    }

    @Override
    protected void onResume() {
        super.onResume();
        initPlayBar=new InitPlayBar(playBar,this);
        initPlayBar.initPlaybar();
        if(isOnStart){
            isOnStart=false;
        }else {
            initAdapter();
        }
        playBar.startMsgReceiver();
        localReceiver=new LocalReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("conchmusic.conchmusicclient.downloadsuccess");
        LocalMusicActivity.this.registerReceiver(localReceiver,filter);
        Log.i("onresume","resume");
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflaterLocal=getMenuInflater();
        inflaterLocal.inflate(R.menu.local_menu_actinbar,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.start_local_search_activity:
                Intent SsearchIntent=new Intent(LocalMusicActivity.this,SearchActivity.class);
                startActivity(SsearchIntent);
                return true;
            case R.id.scan_local_music:
                ScanMusic scanMusic=new ScanMusic();
                List<Song> flushLocalMusic=scanMusic.query(this);
                List<Song> deleteSong=new ArrayList<>();
                for(Song song :flushLocalMusic){
                    for(Song loSong:localMusics){
                        if(song.getLocalSongUrl().equals(loSong.getLocalSongUrl())){
                            deleteSong.add(song);
                        }
                    }
                }
                flushLocalMusic.removeAll(deleteSong);

                if(!flushLocalMusic.isEmpty()){
                    for(Song song:flushLocalMusic){
                        clientControl.addLocalSong(song);
                    }
                }
                if(localMusics.isEmpty()){
                    localMusics=clientControl.findSongs(1);
                    localMusics=getIndexSong(localMusics);
                    localMusics.addAll(flushLocalMusic);
                    listViewAdapter = new LocalListAdapter(this, localMusics);
                    listView.setAdapter(listViewAdapter);
                    //Log.i("flush","flush");
                }else{
                    localMusics=clientControl.findSongs(1);
                    localMusics=getIndexSong(localMusics);
                    listViewAdapter = new LocalListAdapter(this, localMusics);
                    listView.setAdapter(listViewAdapter);
                }
                list=new String[localMusics.size()];
                for(int i=0;i<localMusics.size();i++){
                    list[i]=Integer.toString(localMusics.get(i).getLocalSongId());
                }
                Toast.makeText(LocalMusicActivity.this,"扫描成功",Toast.LENGTH_SHORT).show();;
                return  true;
            case R.id.start_many_select_activity:
                Intent intent1=new Intent();
                intent1.setClass(LocalMusicActivity.this, ManySelectActivity.class);
                startActivity(intent1);
                return  true;
            case android.R.id.home:
                Intent upIntent = NavUtils.getParentActivityIntent(this);
                if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                    TaskStackBuilder.create(this)
                            .addNextIntentWithParentStack(upIntent)
                            .startActivities();
                } else {
                    upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    NavUtils.navigateUpTo(this, upIntent);
                }
                return true;
            case R.id.sort_local_music:
                    initAdapter();
                    return true;

            default:
                return super.onOptionsItemSelected(item);
        }

    }



    public class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle=intent.getExtras();
            String info=bundle.getString("download");
            if(info.equals("success")){
                initAdapter();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(localReceiver);
        playBar.closeMsgReceiver();
    }

    public ArrayList<Song> getIndexSong(List<Song> songs){
        SongGetScanMusic songGetScanMusic=new SongGetScanMusic(songs);
        ArrayList<String> indexSong=songGetScanMusic.getIndexString();
        ArrayList<SortMusic> sortMusics=songGetScanMusic.getmSortList();
        ArrayList<Song> sortSongs=new ArrayList<>();
        sideBar.setIndexText(indexSong);
        Collections.sort(sortMusics,pinyinComparator);
        for(SortMusic sortMusic:sortMusics){
            sortSongs.add(sortMusic.getSong());
        }
        return sortSongs;
    }
    public void initAdapter(){
        localMusics=clientControl.findSongs(1);
        if(!localMusics.isEmpty()){
            localMusics=getIndexSong(localMusics);
            listViewAdapter = new LocalListAdapter(this, localMusics);
            listView.setAdapter(listViewAdapter);
            list=new String[localMusics.size()];
            for(int i=0;i<localMusics.size();i++){
                list[i]=Integer.toString(localMusics.get(i).getLocalSongId());
            }
        }
    }
    public Intent playMusic(int position,String[] list){
        Intent intent=new Intent();
        intent.putExtra("action","playDirect");
        intent.putExtra("posit",position);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(LocalMusicActivity.this.getPackageName());
        return intent;
    }
    public void notifyLocalMusic(){
        initAdapter();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        LocalMusicActivity.this.finish();
    }
}

